package com.powernode.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.QueueConstant;
import com.powernode.constant.SendConstant;
import com.powernode.domain.User;
import com.powernode.dto.SmsDto;
import com.powernode.mapper.UserMapper;
import com.powernode.model.SmsModel;
import com.powernode.service.UserService;
import com.powernode.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.UnsupportedEncodingException;
import java.time.Duration;
import java.util.Date;
import java.util.Random;

/**
 * 内容:
 * 作者: cy
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    Random random = new Random();

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;




    /**
     * 更新会员信息
     *
     * @param user
     */
    @Override
    public void updateMemberInfo(User user) {
        log.info("更新会员的信息{}", JSON.toJSONString(user));
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String ip = requestAttributes.getRequest().getRemoteAddr();
        user.setModifyTime(new Date());
        user.setUserLasttime(new Date());
        user.setUserLastip(ip);
        userMapper.update(user, new LambdaQueryWrapper<User>()
                .eq(User::getUserId, user.getUserId())
        );
    }

    /**
     * 发送手机验证码
     * 1.生成一个code
     * 2.存入redis
     * 3.放mq
     *
     * @param smsDto
     */
    @Override
    public void sendSms(SmsDto smsDto) {
        String code = createCode();
        String phonenum = smsDto.getPhonenum();
        // 存入redis
        redisTemplate.opsForValue().set(SendConstant.PHONE_PREFIX + phonenum, code, Duration.ofSeconds(180));
        // 组装一个对象 放mq  手机号  模板SMS_203185255 签名ego商城  变量替换
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        String param = jsonObject.toJSONString();

        SmsModel smsModel = new SmsModel();
        smsModel.setPhoneNumbers(phonenum);
        smsModel.setSignName("ego商城");
        smsModel.setTemplateCode("SMS_203185255");
        smsModel.setTemplateParam(param);
        // 放mq
        rabbitTemplate.convertAndSend(QueueConstant.PHONE_SEND_QUEUE, JSON.toJSONString(smsModel));
    }

    /**
     * 保存手机号
     *
     * @param smsDto
     */
    @Override
    public void savePhone(SmsDto smsDto) {
        // 校验
        String code = smsDto.getCode();
        if (!StringUtils.hasText(code)) {
            throw new IllegalArgumentException("code不能为空");
        }
        String realCode = redisTemplate.opsForValue().get(SendConstant.PHONE_PREFIX + smsDto.getPhonenum());
        if (!StringUtils.hasText(realCode)) {
            throw new IllegalArgumentException("验证码失效，请重新发送");
        }
        if (!realCode.equals(code)) {
            // 将redis的验证码删掉
            redisTemplate.delete(SendConstant.PHONE_PREFIX + smsDto.getPhonenum());
            throw new IllegalArgumentException("验证码不正确，请重新发送");
        }
        redisTemplate.delete(SendConstant.PHONE_PREFIX + smsDto.getPhonenum());
        // 保存手机号
        User user = new User();
        user.setUserMobile(smsDto.getPhonenum());
        String openId = AuthUtil.getOpenId();
        userMapper.update(user, new LambdaQueryWrapper<User>()
                .eq(User::getUserId, openId)
        );
    }
    private String createCode() {
        int i = random.nextInt(9000) + 1000;
        System.out.println(i);
        return String.valueOf(i);
    }
}
